package com.wantupai.mvp.framework;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;


import com.wantupai.mvp.mvp.MvpPresenter;
import com.wantupai.mvp.mvp.MvpView;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public abstract class MvpBasePresenter<V extends MvpView> implements MvpPresenter<V>
{

    private Context mContext;
    private WeakReference<V> weakView;
    private V proxyView;

    public MvpBasePresenter(Context context)
    {
        mContext = context;
    }

    public MvpBasePresenter(Fragment fragment)
    {
        this(fragment.getActivity());
    }

    @Override
    public void attach(V view)
    {
        weakView = new WeakReference<V>(view);
        MvpViewInvocationHandler invocationHandler = new MvpViewInvocationHandler(this.weakView.get());
        // 在这里采用动态代理
        proxyView = (V) Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces(), invocationHandler);
    }

    @Override
    public void detach()
    {
        if (this.weakView != null)
        {
            this.weakView.clear();
            this.weakView = null;
        }
    }

    protected final Context getContext()
    {
        return mContext;
    }

    protected final V getView()
    {
        return proxyView;
    }

    @Override
    public void destory()
    {

    }

    /**
     * 用于检查View是否为空对象
     *
     * @return
     */
    public boolean isAttachView()
    {
        if (this.weakView != null && this.weakView.get() != null)
        {
            return true;
        }
        return false;
    }

    private class MvpViewInvocationHandler implements InvocationHandler
    {
        private MvpView mvpView;

        public MvpViewInvocationHandler(MvpView mvpView)
        {
            this.mvpView = mvpView;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
        {
            if (isAttachView())
            {
                return method.invoke(mvpView, args);
            }
            return null;
        }
    }

    @Override
    public void onCreate(Bundle bundle)
    {

    }

    @Override
    public void onStart()
    {

    }

    @Override
    public void onResume()
    {

    }

    @Override
    public void onPause()
    {

    }

    @Override
    public void onStop()
    {

    }

    @Override
    public void onRestart()
    {

    }

}
